from os import error
from flask import Blueprint,render_template, request,session,redirect
from config import conn,cur,mutex ,r as redis
import datetime

Diet = Blueprint('Diet',__name__)
 
@Diet.route('/',methods=["GET", "POST"])
def index():
    id = session.get('id') 
    name = session.get('name')

    sqlstr='select TOP 10 * from diet  where patient_id= \'' + str(id)+'\' order by date desc'
    print(sqlstr)
    cur.execute(sqlstr)
    result = cur.fetchall()
    
    return render_template('/Diet/index.html',id =id,name=name,data=result )



@Diet.route('/updateDiets',methods=["GET", "POST"])
def updateDiets():
    if request.method == "POST":
        fname = request.form.get("fname")
        calories = request.form.get("calories")
        weight = request.form.get("weight")
        date = request.form.get("date")
    id = session.get('id') 
    try:
        sqlstr = 'select * from diet  where patient_id= \'' + str(id) +'\' and date = \'' +date+'\''
        print(sqlstr)
        mutex.acquire()
        cur.execute(sqlstr)
        row=cur.fetchone()
        print(row)
        conn.commit()
        mutex.release()
        if row is not None:
            # 更新
            print("1111")
            sqlstr = ' UPDATE diet SET food = \''+ str(fname) +'\' ,calorie = \''+ calories +'\',weight = \''+ weight +'\',date = \''+ date +'\'  where patient_id= \'' + str(id) +'\' and date = \'' +date+'\''
            print(sqlstr)
            mutex.acquire()
            cur.execute(sqlstr)
            conn.commit()
            mutex.release()
        else:
            # 插入
            print("2222")
            sqlstr='insert into diet (patient_id,food,calorie,weight,date) VALUES (\''+str(id)+'\',\''+str(fname)+'\',\''+calories+'\',\''+weight+'\',\''+date+'\' )'
            print(sqlstr)
            mutex.acquire()
            cur.execute(sqlstr)
            conn.commit()
            mutex.release()

        return  {'message':"success!"}
    except error:
        return  {'message':error}

@Diet.route('/logout',methods=["GET", "POST"])
def logout():
    session.clear()
    return {
        'message':"success!"
    }


@Diet.before_request
def before():
    if session.get('id') is None:
        return redirect('/Login/',code=301)
    else:
        pass